import echarts from "utils/echarts";
import { Toast } from "vant";
import { scrollMixin } from "../../utils/mixin";
import { posterMixin } from "../../utils/poster"; //海报
import yzGoodsposter from "components/ui_components/yz_goodsPoster";
export default {
  mixins: [scrollMixin, posterMixin], //加载更多
  data() {
    return {
      fans_type: 1,
      extension_type: "",
      available_type: "",

      income_page: "",
      background_color: "",
      income_statistic: [],
      income_dynamic: {},
      fans_fission: {},
      extension_order: {},
      // 佣金记录
      recordType: '',
      mailLanguage: [],
      // 分销等级
      mail_distrbution_name: '',
      //分销
      mail_commission: '',
      //佣金
      mail_commission_amount: '',
      // 推广粉丝加载更多
      fansPage: 1,
      // 佣金数组
      commissionArr: {},
      // 插件弹窗
      show: false,
      plugin_data: null,
      //分销比例
      first_level: 0,
      //我的粉丝
      count: 0,
      //搜索key
      searchKey: '',
      order_status: null,
      Commission_status: null,
      option1: [
        { text: '请选择', value: 0 },
        { text: '待付款', value: 1 },
        { text: '待发货', value: 2 },
        { text: '待收货', value: 3 },
        { text: '已完成', value: 4 },
        { text: '已关闭', value: 5 },
      ],
      option2: [
        { text: '请选择', value: 0 },
        { text: '预计佣金', value: 1 },
        { text: '未结算', value: 2 },
        { text: '已结算', value: 3 },
        { text: '未提现', value: 4 },
        { text: '已提现', value: 5 },
        { text: '无效', value: 6 },
      ],
      // 佣金记录数组
      Commission_record: [],
      // 佣金设置开关
      Commission_record_set: [],
      // 打开详细的订单id
      display:'',
      subjectColor:'#ffc11e',
      boxShow:false,
      agent_level:[],
      active:1,
      diyname:[],
      agentSetTitle:''
    };
  },
  activated() {
    window.scroll(0, 0);
    this.tabChange('fans_type', '')
    this.initMailLanguage();
    this.getData();
    this.getcommissionOrders();
    require("@/assets/css/icon.scss");
    this.subjectColor = JSON.parse(localStorage.getItem("yz_basic_info")).theme_color
  },
  methods: {
    navTap(item,index,ind){
      this.$set(this.Commission_record.data[index], 'commissionTabs', ind);
    },
    toggle(e,item){
      if (this.display == item.id) {
        this.display = "";
        return;
      }
      this.display = item.id;
    },
    changeStatus(e) {
      console.log(e)
    },
    changeStatus1(e) {
      console.log(e)
      console.log(this.option2[this.Commission_status])
    },
    toastMethod(type) {
      let msg = ''
      if (type == 0) {
        // 直推客户数量，点击跳转到我的客户列表；
        this.$router.push(this.fun.getUrl("myRelationship"));
        return
      } else if (type == 1) {
        msg = '直推客户购买的订单总额'
      } else if (type == 2) {
        msg = `累计分销${this.mail_commission_amount}=预计${this.mail_commission_amount}+未结算${this.mail_commission_amount}+已结算${this.mail_commission_amount}，不含无效${this.mail_commission_amount}，因预计${this.mail_commission_amount}可能会变成无效${this.mail_commission_amount}，故累计${this.mail_commission_amount}数据会有所变化`
      } else if (type == 3) {
        msg = `客户下单后根据设置计算的推广者预计获得的${this.mail_commission_amount}，并非实际获得${this.mail_commission_amount}，如订单退款关闭则变更为无效${this.mail_commission_amount}。`
      } else if (type == 4) {
        msg = `客户订单完成后，获得未结算${this.mail_commission_amount}，满足结算期即可变更为结算${this.mail_commission_amount}`
      } else if (type == 5) {
        msg = `客户订单完成并满足结算期后推广者实际获得的${this.mail_commission_amount}。`
      }
      this.$dialog.alert({ message: msg }).then(() => {

      });
    },
    initMailLanguage() {
      this.mailLanguage = this.fun.initMailLanguage();
      this.fun.setWXTitle(this.fun.setMailLanguage("分销商", this.mailLanguage.commission ? this.mailLanguage.commission.agent : ""));
      this.mail_distrbution_name = this.fun.setMailLanguage("分销等级", this.mailLanguage.commission.level_name);
      this.mail_commission = this.fun.setMailLanguage("分销", this.mailLanguage.commission.commission);
      this.mail_commission_amount = this.fun.setMailLanguage("佣金", this.mailLanguage.commission.commission_amount);
      this.agentSet();
    },
    resetInitMailLanguage(){
      this.fun.setWXTitle(this.diyname ? this.diyname.agent : "");
      this.mail_distrbution_name = this.diyname.level_name;
      this.mail_commission = this.diyname.commission;
      this.mail_commission_amount = this.diyname.commission_amount;
      this.agentSet();
    },
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      console.log(this.recordType,'wwwwwwwww1')
      if (this.recordType == 1) {
        if (this.extension_order.current_page >= this.extension_order.last_page) {
          this.isLoadMore = false;
        } else {
          this.extension_order.current_page += 1;
          $http
            .get("finance.income-page.extension", {
              page: this.extension_order.current_page,
              extension_type: this.recordType
            }," ")
            .then(res => {
              this.isLoadMore = true;
              if (res.result === 1) {
                let nextPageData = res.data.data;
                this.extension_order.data = this.extension_order.data.concat(nextPageData);
              } else {
                this.isLoadMore = false;
              }
            });
        }
      }else{
        console.log(this.Commission_record)
        if (this.Commission_record.current_page >= this.Commission_record.last_page) {
          this.isLoadMore = false;
        } else {
          this.Commission_record.current_page += 1;
          let json = {
            search: this.searchKey,
            commission_type: this.Commission_status,
            order_status: this.order_status,
            page:this.Commission_record.current_page
          }
          let urlstr;
          if(this.$route.name == 'Newdistribution'){
            urlstr = 'plugin.suggest.api.new-commission.get-commission-orders';
          }else{
            urlstr = 'plugin.commission.api.new-commission.get-commission-orders';
          }
          $http
            .get(urlstr, json," ")
            .then(response => {
              this.isLoadMore = true;
              if (response.result === 1) {
                // console.log('wwwwwwwwww',response.data.orders)
                let nextPageData = response.data.orders.data;
                this.Commission_record.data = this.Commission_record.data.concat(nextPageData);
              } else {
                this.isLoadMore = false;
              }
            });
        }
      }

    },
    btnSearch() {
      this.Commission_record = [];
      this.isLoadMore = false;
      this.getcommissionOrders();
    },
    // checkCommission_status(status){
    //   if(status == '0') return ''
    //   if(!status) return ''
    //   return status -1
    // },
    // checkOrder_status(status){
    //   console.log(status,'ddddddddd')
    //   //已结算 1,未结算 2,已提现 -1
    //   if(status == 2){
    //     return 1
    //   }else if(status == 1){
    //     return 2
    //   }else if(status == 4){
    //     return '-1'
    //   }else{
    //     return status
    //   }
    // },
    getcommissionOrders() {
      let json = {
        search: this.searchKey,
        commission_type: this.Commission_status,
        order_status: this.order_status
      }
      let urlstr;
      if(this.$route.name == 'Newdistribution'){
        urlstr = 'plugin.suggest.api.new-commission.get-commission-orders';
      }else{
        urlstr = 'plugin.commission.api.new-commission.get-commission-orders';
      }
      $http
        .get(urlstr, json," ")
        .then(response => {
          if (response.result === 1) {
            console.log(response.data, 'dddddd')
            this.Commission_record = response.data.orders;
            this.Commission_record_set = response.data.set;
            this.isLoadMore = true;
          } else {
            Toast(response.msg);
          }
        });
    },
    getData() {
      let urlstr;
      if(this.$route.name == 'Newdistribution'){
        urlstr = 'plugin.suggest.api.new-commission.get-commission';
      }else{
        urlstr = 'plugin.commission.api.new-commission.get-commission';
      }
      $http
        .get(urlstr, {},"loading")
        .then(response => {
          if (response.result === 1) {
            console.log(response.data)
            this.boxShow = true;
            if (!response.data.member.yz_member && !response.data.member.yz_member.is_agent) {
              this.$dialog
                .confirm({ message: "请先申请成为推广员" })
                .then(() => {
                  this.$router.replace(this.fun.getUrl("ExtensionApply", {}));
                })
                .catch(() => {
                  this.$router.go(-1);
                });
              return;
            }
            if(this.$route.name == 'Newdistribution'){
              this.diyname = response.data.diy_name;
              this.resetInitMailLanguage();
            }
            this.userName = response.data.member.nickname;
            this.vipId = response.data.member.uid;
            this.userAvatar = response.data.member.avatar;
            this.commissionArr = response.data.commission;
            this.plugin_data = response.data.plugin_data;
            this.count =this.commissionArr.customer;
            this.first_level = Number(response.data.agent_level.first_level);
            this.agent_level = response.data.agent_level;
            console.log(this.agent_level,'dddd111')
          } else {
            Toast(response.msg);
          }
        });
    },
    agentSet(){
      if(this.$route.name == 'Newdistribution'){
        return this.agentSetTitle = this.diyname.agent
      }
      if(this.mailLanguage.commission && this.mailLanguage.commission.agent){
        return this.agentSetTitle = this.mailLanguage.commission.agent
      }else{
        return this.agentSetTitle = '分销商'
      }
    },
    WithdrawalTo(){
      this.$router.push(this.fun.getUrl('withdrawal', {}));
    },
    pluginGoto(item) {
      // 插件跳转
      if (!item.name) {
        this.$router.push(this.fun.getUrl(item.url, { fromHome: 1 }));
        return;
      }
      if (item.name == "article") {
        this.$router.push(
          this.fun.getUrl(item.url, {
            id: "0"
          })
        );
      } else if (item.url == "liveList") {
        this.$router.push(this.fun.getUrl(item.url, { from: 1 }));
      } else if (item.name == "courier") {
        window.localStorage.setItem("couriername", item.title);
        this.$router.push(this.fun.getUrl(item.url));
      } else if (item.name == "m-erweima") {
        // 海报
        this.openQrCode("block");
      } else if (item.name == "supplier") {
        this.$router.push(
          this.fun.getUrl(item.url, {
            uid: this.supplier_id
          })
        );
      } else {
        this.$router.push(this.fun.getUrl(item.url, { fromHome: 1 }));
      }
    },
    tabChange(type, data_type) {
      if (type === "fans_type") {
        this.fans_type = data_type;
        this.getFans(data_type);
      } else if (type === 'recordType') {
        this.recordType = data_type;
        this.Commission_record = [];
        this.isLoadMore = false;
        this.getcommissionOrders()
      } else if (type === 'record_fans') {
        this.recordType = data_type;
        this.isLoadMore = false;
        this.getFansRecord(data_type)
      }
    },
    getFansRecord(data_type) {
      $http.get("finance.income-page.extension", { extension_type: data_type }, "loading").then(response => {
        if (response.result === 1) {
          console.log(response.data)
          this.isLoadMore = true;
          this.extension_order = response.data;
        } else {
          Toast(response.msg);
        }
      });
    },
    getFans(data_type) {
      $http.get("finance.income-page.fans-charts", { charts_type: data_type }, "loading").then(response => {
        if (response.result === 1) {
          this.fans_fission = response.data;
          this.$nextTick(() => {
            if (data_type === "1") {
              this.initOrderEcharts();
            } else {
              this.initFansEcharts();
            }
          });
        } else {
          Toast(response.msg);
        }
      });
    },
    initOrderEcharts() {
      if (!document.getElementById("echats-fans-line")) {
        return;
      }
      let $echartsDOM = document.getElementById("echats-fans-line");
      let myEcharts = echarts.init($echartsDOM);
      let maxMoney = Math.max(...this.fans_fission.orderCountSeries) || 50;
      let maxCount = Math.max(...this.fans_fission.orderPriceSeries) || 50;
      let intervalMoney = maxMoney / 5 || 5;
      let intervalCount = maxCount / 5 || 5;
      let option = {
        tooltip: {
          trigger: "axis"
        },
        toolbox: {
          feature: {
            magicType: { show: true, type: ["line", "bar"] },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: ["订单金额", "订单数量"]
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.fans_fission.x_axis
        },
        yAxis: [
          {
            type: "value",
            name: "订单金额",
            min: 0,
            max: maxCount,
            interval: intervalCount
          },
          {
            type: "value",
            name: "订单数量",
            min: 0,
            max: maxMoney,
            interval: intervalMoney
          }
        ],
        series: [
          {
            name: "订单金额",
            type: "bar",
            color: "#f19c70",
            data: this.fans_fission.orderPriceSeries
          },
          {
            name: "订单数量",
            type: "line",
            yAxisIndex: 1,
            color: "#77c399",
            data: this.fans_fission.orderCountSeries
          }
        ]
      };
      myEcharts.setOption(option);
    },
    initFansEcharts() {
      if (!document.getElementById("echats-fans")) {
        return;
      }
      let $echartsDOM = document.getElementById("echats-fans");
      let myEcharts = echarts.init($echartsDOM);
      let maxMoney = Math.max(...this.fans_fission.totalFansSeries) || 50;
      let maxCount = Math.max(...this.fans_fission.fansNewSeries) || 50;
      let intervalMoney = maxMoney / 5 || 5;
      let intervalCount = maxCount / 5 || 5;
      let option = {
        tooltip: {
          trigger: "axis"
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        legend: {
          data: ["粉丝总数", "单日新增粉丝"]
        },
        grid: {
          left: "2%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.fans_fission.x_axis
        },
        yAxis: [
          {
            type: "value",
            name: "总数",
            min: 0,
            max: maxMoney,
            interval: intervalMoney
          },
          {
            type: "value",
            name: "单日",
            min: 0,
            max: maxCount,
            interval: intervalCount
          }
        ],
        series: [
          {
            name: "粉丝总数",
            type: "line",
            color: "#77c399",
            data: this.fans_fission.totalFansSeries
          },
          {
            name: "单日新增粉丝",
            type: "line",
            yAxisIndex: 1,
            color: "#f19c70",
            data: this.fans_fission.fansNewSeries
          }
        ]
      };
      myEcharts.setOption(option);
    },
    timestampToTime: function (timestamp) {
      if (!Number(timestamp) || timestamp == "") {
        return "";
      }
      let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes() + ":";
      let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
  },
  components:{
    yzGoodsposter
  }
};